<template>
  <div class="form-container" :class="{ 'page-container': !inModal }">
    <page-form :model="form" layout="vertical" div="true" ref="formRef">
      <card class="add-info-card" title="车辆信息" toggle>
        <car-info-block :carInfo="carInfo" :fieldList="fieldList" />
      </card>
      <card class="add-info-card" title="保养单信息" toggle>
        <!-- <a-alert style="margin-bottom: 16px"> 创建保养仅作为信息的记录，不占用车辆库存，支持正常排车。 </a-alert> -->
        <page-form-row>
          <page-form-item field="siteId" label="保养单关联门店" required :rules="{ required: true, message: '请选择保养单关联门店' }">
            <remote-select v-model="form.siteId" :initStr="form.siteId ? form.siteName : ''" placeholder="请选择" type="site_listBystaff" />
          </page-form-item>
          <page-form-item field="maintenanceShopId" label="修理厂">
            <template #label-extra>
              <!-- 新增供应商 -->
              <i-add-supplier typeText="修理" supplierType="1" @addOk="addSupplierOk" />
            </template>
            <remote-select
              v-model="form.maintenanceShopId"
              type="supplier_list"
              :params="{
                supplierType: 1,
                idList: form.maintenanceShopId ? [form.maintenanceShopId] : undefined,
                status: 1,
              }"
            />
          </page-form-item>
          <page-form-item />
          <page-form-item field="entranceKilometre" label="本次保养里程">
            <i-input-number @blur="onBlurKilometre" v-model="form.entranceKilometre" unit="公里" :precision="0" />
          </page-form-item>
          <page-form-item
            field="maintenanceLimitMileage"
            label="保养间隔里程"
            labelTooltipContent="用于计算下次保养里程，下次保养里程=本次保养里程+保养间隔里程。"
          >
            <i-input-number @blur="onBlurKilometre" v-model="form.maintenanceLimitMileage" unit="公里" :precision="0" />
          </page-form-item>
          <page-form-item
            field="estimatedKilometre"
            label="下次保养里程"
            :rules="{ required: true, message: '请输入下次保养里程' }"
            size="1/3"
          >
            <i-input-number v-model="form.estimatedKilometre" unit="公里" :precision="0" />
          </page-form-item>
          <page-form-item field="entranceDate" label="本次保养日期">
            <i-date-picker class="w-full" v-model="form.entranceDate" @change="onBlurDay" value-format="YYYY-MM-DD" />
          </page-form-item>
          <page-form-item
            field="maintenanceLimitDay"
            label="保养间隔时间"
            labelTooltipContent="用于计算下次保养日期，下次保养日期=本次保养日期+保养间隔时间。"
          >
            <i-input-number @blur="onBlurDay" v-model="form.maintenanceLimitDay" unit="天" precision="0" max="9999" />
          </page-form-item>
          <page-form-item field="estimatedTime" label="下次保养日期" size="1/3">
            <i-date-picker class="w-full" v-model="form.estimatedTime" value-format="YYYY-MM-DD" />
          </page-form-item>
          <page-form-item label="承租人信息">
            <remote-select
              :disabled="pageParams.byOrder"
              v-model="form.memberId"
              :params="{
                oldId: form.memberId,
                carId: form.carId,
                orderTypeList: [3],
              }"
              type="member_list_label"
              :mustParentShow="!form.carId"
              mustParentTip="请先选择车牌号"
              @change="changeMemberFn"
            />
          </page-form-item>
          <page-form-item label="关联订单号">
            <template #label-extra>
              <span class="text-jcr"> 交车人：{{ form.giveStaffName || '-' }} </span>
            </template>
            <a-select
              allow-search
              placeholder="请选择"
              :disabled="pageParams.byOrder"
              v-model="form.orderId"
              :mustParentShow="!form.carId"
              mustParentTip="请先选择车牌号"
              @change="changeOrderIdFn"
              allow-clear
              popup-container=".form-container"
            >
              <a-option v-for="item in shortOrderIdList" :key="item.orderId" :value="item.orderId" :label="item.label">
                {{ item.label }}
              </a-option>
            </a-select>
          </page-form-item>

          <page-form-item field="undertakerId" label="负责人">
            <remote-select
              v-model="form.undertakerId"
              placeholder="请选择"
              :mountedLoad="!!form.carId"
              type="staff_authOrg"
              :params="{ oldId: form.undertakerId, siteIdList: carSiteList }"
            />
          </page-form-item>
          <page-form-item field="remark" label="备注" size="2/3">
            <i-input textarea v-model="form.remark" auto-size />
          </page-form-item>
          <page-form-item field="fileIdList" label="上传照片" size="2/3">
            <upload-img v-model="form.fileIdList" limit="30" />
          </page-form-item>
        </page-form-row>
      </card>
      <card class="add-info-card" title="保养费用" :showDivider="false">
        <page-form-row>
          <page-form-item field="maintenanceAmount" label="保养费" size="1/3">
            <template #label-extra v-if="assetFeeInfo.feeStatus == 1">
              <a-tag color="orangered">
                <template #icon>
                  <icon-exclamation-circle-fill />
                </template>
                已付款无法编辑
              </a-tag>
            </template>
            <i-input-number :disabled="assetFeeInfo.feeStatus == 1" v-model="form.maintenanceAmount" unit="元" :precision="2" />
          </page-form-item>
          <page-form-item field="remark" label="费用备注" size="2/3">
            <i-input textarea v-model="form.feeRemark" auto-size />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
  </div>
  <page-form-footer :ok-loading="okLoading" v-if="inModal == false" @ok="submitFn" />
</template>

<script setup name="CarMaintenanceForm">
  import IAddSupplier from '@/components/input/i-add-supplier.vue'

  import { maintenanceDetail, maintenanceAdd, maintenanceEdit, getRelationOrderNo } from '@/api/asset/maintenance'
  import { getCarDetail, orderCarInfo } from '@/api/asset/car'
  import useNavigate from '@/hooks/useNavigate'
  import { ref, onMounted } from 'vue'
  import { Modal } from '@arco-design/web-vue'
  import dayjs from 'dayjs'
  import { useRoute } from 'vue-router'
  import useUserStore from '@/store/modules/user'
  import { ruleDetail } from '@/api/system/backlogrule'

  const userStore = useUserStore()
  const { navigateBack } = useNavigate()
  const route = useRoute()
  const shortOrderIdList = ref([])
  const props = defineProps({
    inModal: Boolean,
    params: Object,
  })

  const form = ref({})
  // 初始化参数
  const pageParams = ref({})
  const initPageParams = () => {
    if (props.inModal) {
      // 车辆详情（新增&编辑）
      pageParams.value = { ...props.params }
    } else {
      if (route.query.page == 'longOrder') {
        pageParams.value = {
          orderId: route.params.id,
          page: 'longOrder',
          byOrder: true,
        }
      } else {
        pageParams.value = {
          carId: route.params.id,
          page: 'carList',
        }
      }
    }
  }

  // 长租类型车辆信息不展示保养单号
  const fieldList = ref([
    { label: '车架号', prop: 'vin' },
    { label: '车辆当前归属门店', prop: 'siteName' },
    { label: '归属车场', prop: 'libraryName' },
    { label: '保养单号', prop: 'maintenanceNo' },
  ])

  // 清空订单相关信息
  const clearOrderInfo = () => {
    form.value.orderId = null
    form.value.orderNo = null
    form.value.giveStaffId = null
    form.value.orderType = null
    form.value.giveStaffName = null
  }

  // 更换承租人
  const changeMemberFn = (value) => {
    let defaultSelectFirst = false
    if (value) {
      defaultSelectFirst = true
    }
    getOrderNumber(defaultSelectFirst)
  }

  /**
   * defaultSelectFirst 是否默认选中第一个
   */
  const getOrderNumber = (defaultSelectFirst = false) => {
    getRelationOrderNo({
      carId: form.value.carId,
      orderTypeList: [3],
      memberId: form.value.memberId,
      useAuth: 1,
      oldOrderType: form.value.orderType,
      oldOrderId: form.value.orderId,
    }).then((res) => {
      if (res.result?.length > 0) {
        res.result.forEach((item) => {
          item.label = '【' + item.orderTypeStr + '】' + item.orderNo
          item.value = item.orderId
        })
        shortOrderIdList.value = res.result
      } else {
        shortOrderIdList.value = []
        clearOrderInfo()
      }
      // 处理默认选中逻辑
      if (shortOrderIdList.value?.length > 0) {
        // 当前存在已选择的订单时，判断是否存在于当前的列表中，如存在，则不再重新给与默认值
        if (form.value.orderId) {
          const hasSameOrderId = shortOrderIdList.value.some((item) => item.orderId == form.value.orderId)
          if (hasSameOrderId) {
            // 存在相同订单，则不再默认选中第一个
            defaultSelectFirst = false
          }
        }
        // 默认选中第一个
        if (defaultSelectFirst) {
          const first = shortOrderIdList.value[0]
          form.value.orderId = first.orderId //默认第一个
          form.value.orderNo = first.orderNo
          form.value.giveStaffId = first.giveStaffId //默认第一个
          form.value.orderType = first.orderType
          form.value.giveStaffName = first.giveStaffName
          // 如果当前不存在承租人
          if (!form.value.memberId) {
            // 承租人
            form.value.memberId = first.memberId
            // 重新获取关联订单号列表
            getOrderNumber(defaultSelectFirst)
          }
        }
      }
    })
  }
  // 添加供应商成功
  const addSupplierOk = (id) => {
    form.value.maintenanceShopId = id
  }

  // 编辑时，获取详情
  const carInfo = ref({})
  const assetFeeInfo = ref({})
  const carSiteList = ref()
  const getDetail = () => {
    maintenanceDetail({ id: pageParams.value.id }).then((res) => {
      assetFeeInfo.value = res.result.assetFeeInfo || {}
      form.value.maintenanceShopId = res.result.maintenanceShopId ? res.result.maintenanceShopId.toString() : ''
      form.value = Object.assign({}, res.result, {
        // 回填系统待办事项配置的保养间隔里程
        maintenanceLimitMileage: maintenanceLimitMileage.value,
        // 回填系统待办事项配置的保养间隔时间
        maintenanceLimitDay: maintenanceLimitDay.value,
      })
      carInfo.value = res.result
      carSiteList.value = [carInfo.value.siteId]

      getOrderNumber() //查 关联订单号列表
    })
  }

  const preSubmitFn = (noticeSuccess) => {
    return new Promise((resolve, reject) => {
      if (form.value.id) return resolve()
      let preSubmitInfo = undefined
      // 下次保养里程小于车辆上下次保养里程的情况
      if (form.value.estimatedKilometre < carInfo.value.estimatedKilometre) {
        preSubmitInfo = '新增保养的下次保养里程小于车辆上的下次保养里程，请确认是否新增？'
      }
      // 下次保养日期小于车辆上的情况
      if (dayjs(form.value.estimatedTime).isBefore(dayjs(carInfo.value.estimatedTime))) {
        preSubmitInfo = '新增保养的下次保养日期小于车辆上的下次保养日期，请确认是否新增？'
      }
      if (preSubmitInfo) {
        Modal.confirm({
          title: '提示',
          simple: true,
          content: preSubmitInfo,
          onOk: () => resolve(),
          onCancel: () => {
            reject()
            if (props.inModal) {
              // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
              noticeSuccess(false)
              return
            }
          },
        })
      } else {
        resolve()
      }
    })
  }

  const formRef = ref()
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    formRef.value.validate(async (error) => {
      if (!error) {
        // 提交前置判断
        await preSubmitFn(noticeSuccess)
        okLoading.value = true
        if (pageParams.value.mode == 'edit') {
          form.value.status = carInfo.value.status
          maintenanceEdit({ ...form.value })
            .then((res) => {
              if (props.inModal) {
                // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
                noticeSuccess()
                return
              }
              noticeSuccess()
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
              if (props.inModal) {
                // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
                noticeSuccess(false)
                return
              }
            })
        } else {
          form.value.status = 0
          maintenanceAdd({ ...form.value })
            .then((res) => {
              if (props.inModal) {
                // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
                noticeSuccess()
                return
              }
              noticeSuccess()
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
              if (props.inModal) {
                // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
                noticeSuccess(false)
                return
              }
            })
        }
      } else {
        if (props.inModal) {
          // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
          noticeSuccess(false)
          return
        }
      }
    })
  }

  // 获取车辆详情
  const getCarDetails = () => {
    getCarDetail({ id: pageParams.value.carId }).then((res) => {
      carInfo.value = res.result
      form.value.entranceKilometre = res.result.totalMileage //选车牌号自动带入本次保养里程
      form.value.siteId = res.result.siteId
      form.value.siteName = res.result.siteName
      form.value.carId = res.result.id
      form.value.maintenanceLimitMileage = maintenanceLimitMileage.value
      form.value.maintenanceLimitDay = maintenanceLimitDay.value
      // 如果存在本次保养里程，则默认下次保养里程为本次保养里程+保养间隔里程
      if (form.value.maintenanceLimitMileage && form.value.entranceKilometre) {
        form.value.estimatedKilometre = form.value.maintenanceLimitMileage + form.value.entranceKilometre
      }

      if (!form.value.undertakerId) {
        form.value.undertakerId = userStore.employeeId
      }
      getOrderNumber(true) //查关联订单号列表
    })
  }
  // 获取订单详情=>获取车信息和订单信息
  const getCarInfo = () => {
    orderCarInfo({ id: pageParams.value.orderId, type: 3 }).then((res) => {
      carInfo.value = {
        licenseNo: res.result.licenseNo,
        vin: res.result.vin,
        modelName: res.result.modelName,
        siteName: res.result.siteName,
        libraryName: res.result.libraryName,
      }
      form.value.orderId = res.result.orderId
      form.value.carId = res.result.carId
      form.value.orderNo = res.result.orderCode
      form.value.giveStaffName = res.result.giveStaffName
      form.value.giveStaffId = res.result.giveStaffId
      form.value.siteId = res.result.siteId
      form.value.siteName = res.result.siteName
      form.value.memberId = res.result.memberId
      form.value.memberName = res.result.memberName
      form.value.memberPhone = res.result.mememberPhone
      form.value.maintenanceLimitMileage = maintenanceLimitMileage.value
      form.value.maintenanceLimitDay = maintenanceLimitDay.value

      if (!form.value.undertakerId) {
        form.value.undertakerId = userStore.employeeId
      }

      shortOrderIdList.value = [
        {
          label: res.result.orderCode,
          orderNo: res.result.orderCode,
          value: res.result.orderId,
          orderId: res.result.orderId,
        },
      ]
    })
  }
  // 选择关联订单号
  const changeOrderIdFn = (value) => {
    if (value) {
      shortOrderIdList.value.map((item) => {
        if (item.orderId === value) {
          form.value.orderId = item.orderId
          form.value.orderNo = item.orderNo
          form.value.giveStaffId = item.giveStaffId
          form.value.orderType = item.orderType
          form.value.giveStaffName = item.giveStaffName

          // 承租人信息
          form.value.memberId = item.memberId
          form.value.memberPhone = item.memberPhone
          form.value.memberName = item.memberName
        }
      })
    } else {
      clearOrderInfo()
    }
  }
  // 编辑本次保养里程 or 保养间隔里程后，都会重新计算并回填下次保养里程
  const onBlurKilometre = (val) => {
    if (!isNaN(form.value.maintenanceLimitMileage) && !isNaN(form.value.entranceKilometre)) {
      form.value.estimatedKilometre = form.value.maintenanceLimitMileage + form.value.entranceKilometre
    }
  }
  // 编辑本次保养日期 or 保养间隔日期后，都会重新计算并回填下次保养日期
  const onBlurDay = (val) => {
    if (!isNaN(form.value.maintenanceLimitDay) && form.value.entranceDate) {
      form.value.estimatedTime = dayjs(form.value.entranceDate).add(form.value.maintenanceLimitDay, 'day').format('YYYY-MM-DD')
    }
  }

  // 初始化保养间隔时间、里程
  const maintenanceLimitMileage = ref(undefined)
  const maintenanceLimitDay = ref(undefined)
  const initMaintenanceLimitDay = () => {
    return new Promise((resolve, reject) => {
      ruleDetail()
        .then((res) => {
          if (res.code == 200) {
            // 回填系统待办事项配置的保养间隔里程
            maintenanceLimitMileage.value = res.result?.maintenanceLimitMileage
            // 回填系统待办事项配置的保养间隔时间
            maintenanceLimitDay.value = res.result?.maintenanceLimitDay
            resolve(res.result.maintenanceLimitDay)
          } else {
            reject(new Error('Failed to fetch maintenance limit day'))
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  onMounted(async () => {
    // 初始化参数
    initPageParams()
    await initMaintenanceLimitDay()

    // 编辑
    if (pageParams.value.id) {
      getDetail()
      return
    }
    // 新增不展示保养单号
    fieldList.value = fieldList.value.splice(0, 3)
    // 从订单新增
    if (pageParams.value.orderId) {
      getCarInfo()
    }
    // 从车辆新增
    if (pageParams.value.carId) {
      getCarDetails()
    }
  })

  defineExpose({
    submitFn,
    form,
  })
</script>

<style lang="less" scoped>
  :deep(.upload-item) {
    margin: 0px 16px 0 0;
  }

  .form-container {
    position: relative;
    width: 100%;
    overflow: hidden;
  }

  .operate-list {
    position: absolute;
    right: -236px;
    margin-left: -40px;

    .operate-btn + .operate-btn {
      margin-left: 16px;
    }
  }

  .upload-wrapper {
    padding: 20px 0 0;

    .upload-content {
      width: 40%;
      margin-right: 40px;
    }
  }
  .empty {
    margin-top: 100px;
    text-align: center;
    color: rgba(0, 0, 0, 0.25);
  }
  .text-jcr {
    color: #1890ff;
  }
</style>
